package com.xizi.producer;

import com.xizi.partitioner.MyPartitioner;
import org.apache.kafka.clients.producer.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @author xizizzz
 * @description: TODO
 * @date 2021-7-3下午 12:40
 */
public class InterceptorProducer {
    public static void main(String[] args) throws Exception {
        //1. 创建Kafka生产者的配置信息
        Properties props = new Properties();
        //2. 指定连接的Kafka集群  broker-list
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "zookeeper1:9092");

        //8. key value序列化类
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        //9. 使用自定义分区
        props.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, MyPartitioner.class); // 设置的1号分区

        // 2 构建拦截链
        List<String> interceptors = new ArrayList<>();
        interceptors.add("com.xizi.Interceptor.CounterInterceptor");
        interceptors.add("com.xizi.Interceptor.TimeInterceptor");

        props.put(ProducerConfig.INTERCEPTOR_CLASSES_CONFIG, interceptors);


        //10. 创建生产者对象
        Producer<String, String> producer = new KafkaProducer<>(props);
        //11. 发送数据
        for (int i = 0; i < 10; i++) {
            //指定数据发送到0号分区
            producer.send(new ProducerRecord<>("aaa", "xizi_key", "xizizzz--" + i), new Callback() {
                //回调函数， 该方法会在 Producer 收到 ack 时调用，为异步调用
                @Override
                public void onCompletion(RecordMetadata metadata, Exception exception) {
                    if (exception == null) {
                        System.out.println(metadata.topic() + "--" + metadata.partition() + "--" + metadata.offset());
                    } else {
                        exception.printStackTrace();
                    }
                }
            });
        }
        //11. 关闭资源
        producer.close();
    }
}
